<template>
  <el-select
    :value="valueTitle"
    :clearable="clearable"
    :multiple="multiple"
    :collapse-tags="collapse"
    @remove-tag="handleRemoveTag"
    @clear="clearHandle">
    <el-input
      class="selectInput"
      :placeholder="placeholder"
      v-model="filterText"
    ></el-input>

    <el-option :value="valueId"  :label="label" class="options">
      <el-tree id="tree-option"
               ref="selectTree"
               :accordion="accordion"
               :data="options"
               :show-checkbox="multiple"
               :check-strictly="true"
               :props="props"
               :node-key="props.value"
               :default-expanded-keys="defaultExpandedKey"
               :default-checked-keys="defaultCheckedKeys"
               :default-expand-all="expand"
               :auto-expand-parent="expandParent"
               :expand-on-click-node="expandNode"
               :lazy="lazy"
               :load="loadNodes"
               :filter-node-method="filterNode"
               @node-click="handleCheckClick"
               @check-change="handleCheckClick">

      </el-tree>
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: "TreeSelect",

  props:{
    //配置项
    props:{
      type:Object,
      default:()=>{
        return{
          value:'id',
          label:'title',
          children:'children',
          isLeaf:'leaf'
        }
      }
    },
    //选项列表的数据
    options:{
      type:Array,
      default:()=>{
        return []
      }
    },
    //初始值
    value:{
      type: [String, Number, Boolean, Array],
      default:()=>{
        return []
      }
    },
  //  宽度
    width:{
      type:String,
      default:()=>{
        return '270px'
      }
    },
  //  是否多选
    multiple:{
      type:Boolean,
      default:()=>{
        return true
      }
    },
  //  是否展示复选框
    checkbox:{
      type:Boolean,
      default:()=>{
        return false
      }
    },
  //  多选是否将选中值按文字表示
    collapse:{
      type:Boolean,
      default:()=>{
        return true
      }
    },
  //  是否可清空
    clearable:{
      type:Boolean,
      default:()=>{
        return true
      }
    },

  //  是否显示check
    show:{
      type:Boolean,
      default:()=>{
        return false
      }
    },
  //  是否自动展开
    accordion:{
      type:Boolean,
      default:()=>{
        return false
      }
    },
  //  搜索框的提示
    placeholder:{
      type:String,
      default:()=>{
        return "检索关键字"
      }
    },
  //  是否展开所有节点
    expand:{
      type:Boolean,
      default:()=>{return false}
    },
  //  展开子节点是否需要展开父节点
    expandParent:{
      type:Boolean,
      default:() =>{return true}
    },
  //  是否在点击节点时展开或者收缩节点
    expandNode:{
      type:Boolean,
      default:() =>{return true}
    },

    lazy:{
      type:Boolean,
      default:()=>{return false}
    },
    defaultCheckedKeys:{
      type:Array,
      default:()=>{return []}
    }
  },
  data(){
    return{
      valueTitle:[],//当前选中的label
      valueId:this.value,//当前选中的value
      defaultExpandedKey:[],
      filterText:'',
      label:''
    }
  },

  mounted() {
    this.initTreeSelect()
  },

  methods:{
    /*
      初始化函数
     */
    initTreeSelect(){
      if(this.valueId && !this.multiple)//单选
      {
        var node = this.$refs.selectTree.getNode(this.valueId);
        if(node){
          this.valueTitle = node.data[this.treeProps.label]; // 初始化显示
          this.defaultExpandedKeys = [this.valueId]; // 设置默认展开
          this.$nextTick(() => {
            this.$refs.selectTree.setCurrentKey(this.valueId); // 设置默认选中
          })
        }
      }
      else if(this.valueId && this.multiple) {//多选
        this.defaultExpandedKeys =this.defaultExpandedKey
        this.$nextTick(()=>{
          this.$refs.selectTree.setChecked(this.valueId); // 设置默认选中
        })
      }
      this.initScroll()
    },
    /*
      初始化滚动条
     */
    initScroll(){
      this.$nextTick(()=>{
        let scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
        let scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar')
        scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
        scrollBar.forEach(ele => ele.style.width = 0)
      })
    },
    /*
     单选
     */
    handleNodeClick(node){
        this.valueTitle = node[this.props.label]
        this.valueId =node[this.props.value]
        //返回父组件
        this.$emit('getValue',this.valueId)
        this.defaultExpandedKey=[]
    },
    /*
      多选，节点发生变化时回调
     */
    handleCheckClick(data,checked,childrenCheck){
      this.valueId = this.$refs.selectTree.getCheckedKeys()
      var checkedNodes = this.$refs.selectTree.getCheckedNodes()
      this.valueTitle = checkedNodes.map((node)=>{
        return node[this.props.label]
      })
      this.$emit('getValue',this.valueId)
    },
    /*
      清除选中的选项/checkbox
     */
    clearHandle(){


      this.defaultExpandedKey=[]
      if(this.multiple){
        this.valueId=[]
        this.valueTitle=[]//当前选中的label
        this.$refs.selectTree.setChecked([])
        this.$emit('getValue',[])
      }
      else{
        this.valueId=''//当前选中的value
        this.valueTitle=''
        this.$refs.selectTree.setCurrentKey(null)
        this.$emit('getValue',null)
      }

    },
    /*
      多选中除去任意选中
     */
    handleRemoveTag(val){
      var checkNodes = this.$refs.selectTree.getCheckedNodes();
      var node=checkNodes.find(node => node[this.props.label] ===val)
      this.$refs.selectTree.setChecked(node[this.props.value],false)
    },
    /*
      过滤方法
     */
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /*
      加载节点方法
     */
    loadNodes(node,resolve){
      this.$emit('load',node,resolve)
    },
    /*
    通过key来设置值
     */
    setCheckedKeys(keys){
      this.$refs.selectTree.setCheckedKeys(keys)
      this.setCheckedNodes()
      this.valueId = keys
      this.$emit('getValue',this.valueId)
    },
    /*
    调用key值后回调nodes
     */
    setCheckedNodes(){
      var checkedNodes = this.$refs.selectTree.getCheckedNodes()
      this.valueTitle = checkedNodes.map((node)=>{
        return node[this.props.label]
      })
      // console.log(this.valueTitle)
    }
  },
  watch:{
    value:{
      handler(newValue){
        this.valueId = newValue
        this.initTreeSelect()
      },
      immediate:true,
      deep:true
    },
    filterText(val) {
      this.$refs.selectTree.filter(val);
    }
  },
  computed:{
    selectStyle(){
      return{
        width:`${this.width}`
      }
    }
  }

}
</script>

<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}


.el-scrollbar .el-select-dropdown__item.selected {
  font-weight: normal;
}

/*横向滚动条*/
.el-scrollbar__bar.is-horizontal {
  height: 6px;
  left: 2px;
}

/*纵向滚动条*/
.el-scrollbar__bar.is-vertical {
  /*width: 6px;*/
  /*top: 2px;*/
  display: none;
}

/*字体和大小*/
.custom-tree-node {
  font-family:"Microsoft YaHei";
  font-size: 14px;
  position: relative;
}

/*原生 el-tree-node的div是块级元素，需要改为inline-block，才能显示滚动条 */
.treeSelect .el-tree >.el-tree-node {
  display: inline-block;
  min-width: 100%;
}

ul li ::v-deep .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}

.el-tree-node__label {
  font-weight: normal;
}


.el-tree ::v-deep .is-current .el-tree-node__label {
  color: #1B65B9;
  font-weight: 700;
}

.el-tree ::v-deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}


</style>

<style lang="less">
.el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display:inline-block;
  }
  .el-checkbox__input> .el-checkbox__inner {
    display:none;
  }
}
</style>
